import { useIntersectionObserver } from '@/hooks/use-intersection-observer'
import React, { useEffect } from 'react'
import { Button } from './ui/button'

interface InfiniteScrollProps {
    isManual?: boolean
    hasNextPage: boolean
    isFetchingNextPage: boolean
    fetchNextPage: () => void
}


export default function InfiniteScroll({ isManual, hasNextPage, isFetchingNextPage, fetchNextPage }: InfiniteScrollProps) {
    const { isIntersecting, targetRef } = useIntersectionObserver({
        threshold: 0.5,
        rootMargin: '100px'
    })

    useEffect(() => {
        if (isIntersecting && hasNextPage && !isFetchingNextPage && !isManual) {
            fetchNextPage()
        }
    }, [isIntersecting, hasNextPage, isFetchingNextPage, fetchNextPage, isManual])

    return (
        <div className='flex flex-col items-center gap-4 p-4'>
            <div ref={targetRef} className='h-1'></div>
            {
                hasNextPage ? (
                    isManual && <Button variant="secondary" className='cursor-pointer' disabled={isFetchingNextPage || !hasNextPage} onClick={() => fetchNextPage()}>
                        {isFetchingNextPage ? "Loading..." : "Load More"}
                    </Button>
                ) : <p className='text-xs text-muted-foreground'>You have reached the end of the list</p>
            }
        </div>
    )
}
